//
//  TZSetCell.m
//  wangYiLottery
//
//  Created by mac on 16/3/2.
//  Copyright © 2016年 tz. All rights reserved.
//

#import "TZSetCell.h"

#import "TZSetItemsModel.h"

@interface TZSetCell ()

@end

@implementation TZSetCell

- (void)setCellModel:(TZSetCellModel *)cellModel {
    _cellModel = cellModel;
    
}

- (void)setItemsModel:(TZSetItemsModel *)itemsModel {
    _itemsModel = itemsModel;
    self.textLabel.text = itemsModel.title;
    self.imageView.image = [UIImage imageNamed:itemsModel.icon];
    //获取key中对应的字符串
    NSString *accessoryView = itemsModel.accessoryView;
    //将key对应的字符串转化成一个类
    Class modelClass = NSClassFromString(accessoryView);
    //用类创建一个对象
    UIView *view = [[modelClass alloc] init];
    if ([view isKindOfClass:[UIImageView class]]) {
        //设置图片
        UIImageView *imageView = (UIImageView *)view;
        imageView.image = [UIImage imageNamed:itemsModel.accessoryContent];
        //设置成和图片一样的大小
        [imageView sizeToFit];
    } else if ([view isKindOfClass:[UISwitch class]]) {
        //监听开关
        UISwitch *sw = (UISwitch *)view;
        [sw addTarget:self action:@selector(switchChanges:) forControlEvents:UIControlEventValueChanged];
        //初始化开关的状态
        NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
        sw.on = [ud boolForKey:itemsModel.switchKey];
    }
    //设置右边的View
    self.accessoryView = view;
}

+ (instancetype)settingCellWithTableView:(UITableView *)tableView {
    static NSString *cellID = @"cellID";
    TZSetCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[TZSetCell alloc] init];
    }
    return cell;
}

//开关状态的监听事件
- (void)switchChanges:(UISwitch *)sender {
    //使用偏好设置保存开关状态
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    [ud setBool:sender.isOn forKey:self.itemsModel.switchKey];
    //立即写入
    [ud synchronize];
}

@end
